import { AdvContext, AdvVisitor } from "./adv";
import { Ast, createRootAst } from "./ast";
import { closeApp } from "./closeApp";
import { isSettingCachePage } from "./pages";
import { toSettingCachePage, toSettingPage, toTabLayout } from "./to";
import { PACKAGES } from "./utils";

class CacheCleanVisitor extends AdvVisitor {
    visitTextView(node: Ast, ctx: AdvContext): void {
        if (node.sid === `cache_type` && node.text === `缓存`) {
            const clearNode = node.parent.children.find(it => it.sid === `clear_cache`)
            ctx.close = () => clearNode?.click()
            return;
        }
    }
    visitButton(node: Ast, ctx: AdvContext){
        if(node.sid ===`clear_cache` && node.text === `清理`){
            ctx.close = () => node?.click()
            return;
        }
    }
}

function cacheClean() {
    const visitor = new CacheCleanVisitor()
    const ctx: AdvContext = {}
    while (!ctx.close) {
        const root = createRootAst()
        root.visit(visitor, ctx)
        sleep(1000)
    }
    ctx.close && ctx.close()
}
function max(a: number, b: number) {
    return a > b ? a : b;
}
export function clearCacheOnly(pkg: string) {
    sleep(1000)
    toSettingPage()
    toSettingCachePage()
    if (!isSettingCachePage()) {
        swipe(device.width / 2, device.height * 2 / 3, device.width / 2, max(100, device.height / 2 - 500), 500);
        toSettingCachePage()
    }
    if (!isSettingCachePage()) {
        toastLog(`不在缓存页面`)
        swipe(device.width / 2, device.height * 2 / 3, device.width / 2, max(100, device.height / 2 - 500), 500);
        sleep(1000)
        toSettingCachePage()
    }
    if (!isSettingCachePage()) {
        toastLog(`打开缓存页面失败`)
        return;
    } else {
        cacheClean()
        toastLog(`清理缓存成功`)
    }
    toTabLayout(pkg)
    toastLog(`返回成功，关闭应用`)
}
export function clearCache(pkg: string = PACKAGES.KUAI_SHOU) {
    clearCacheOnly(pkg)
    sleep(1000)
    closeApp(pkg)
}
